#include <iostream>
#include <string>
#include <functional>

class BaseClass {
public:
    virtual void print() = 0;
};

class DerivedA : public BaseClass {
public:
    void print() override {
        std::cout << "DerivedA" << std::endl;
    }
};

class DerivedB : public BaseClass {
public:
    void print() override {
        std::cout << "DerivedB" << std::endl;
    }
};

// 注册类，反射
class ClassRegistry {
public:
    using CreatorFunction = std::function<BaseClass*()>;

    // //单例模式
    // ClassRegistry();
    // static ClassRegistry& getInstance() {
    //     static ClassRegistry instance;
    //     return instance;
    // }

    void registerClass(const std::string& className, CreatorFunction creator) {
        registry_[className] = creator;
    }

//实现了一个工厂函数 createInstance，它根据给定的类名在注册表中查找相应的构造函数，并返回一个基类指针
    BaseClass* createInstance(const std::string& className) {
        auto it = registry_.find(className);
        if (it != registry_.end()) {
            return (it->second)();
        }
        std::cout << "error while create instance " << std::endl;
        return nullptr;//表示创建失败
    }

private:
    // 尝试像RTType中类似的创建单例模式
    ClassRegistry();
    static ClassRegistry& getInstance() {
        static ClassRegistry instance;
        return instance;
    }
    std::unordered_map<std::string, CreatorFunction> registry_;
};

// 全局范围注册
void registerClasses() {
    // 用一个lambda表达式返回对象
    ClassRegistry::getInstance().registerClass("DerivedA", []() { return new DerivedA(); });
    ClassRegistry::getInstance().registerClass("DerivedB", []() { return new DerivedB(); });
}


int main() {
    registerClasses();

    BaseClass* objA = ClassRegistry::getInstance().createInstance("DerivedA");
    if (objA) {
        objA->print();
        delete objA;
    }

    BaseClass* objB = ClassRegistry::getInstance().createInstance("DerivedB");
    if (objB) {
        objB->print();
        delete objB;
    }

    BaseClass* objC = ClassRegistry::getInstance().createInstance("DerivedC");

    return 0;
}
